import namespace from "./namespace";
import EventEmitter from "eventemitter3";

class CommandStack extends EventEmitter {
  constructor() {
    super();
    this.undostack = [];
    this.redostack = [];
  }

  execute(command) {
    if (!command) {
      return;
    }

    this.undostack.push(command);
    command.execute();

    this.redostack = [];

    return this;
  }

  redo() {
    let command = this.redostack.pop();
    if (command) {
      this.undostack.push(command);
      command.redo();
    }

    return this;
  }

  undo() {
    let command = this.undostack.pop();
    if (command) {
      this.redostack.push(command);
      command.undo();
    }
    return this;
  }

  canRedo() {
    return this.redostack.length > 0;
  }

  canUndo() {
    return this.undostack.length > 0;
  }
}

namespace.CommandStack = CommandStack;
